package com.hmall.order.web;

import com.hmall.order.mq.QueueConfig;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private IOrderService orderService;


    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/{id}")
    public Order queryOrderById(@PathVariable("id") Long orderId) {
        Long userId = UserHolder.getUser();
        System.out.println(userId);
        return orderService.getById(orderId);
    }

    @PostMapping
    public Long createOrder(@RequestBody RequestParams params) {
        Long userId = UserHolder.getUser();
        System.out.println(userId);
        Long orderId = orderService.submitOrder(params);
        sendMessage(orderId);
        return orderId;
    }

    private void sendMessage(Long orderId) {
        // 将订单信息发送到延迟队列
        Message message = MessageBuilder.withBody(String.valueOf(orderId).getBytes(StandardCharsets.UTF_8))
                // 10s后过期
                // .setExpiration(String.valueOf(10000 * 6))
                .build();
        rabbitTemplate.convertAndSend(QueueConfig.JAVABOY_QUEUE_NAME, message);
        log.info("订单消息投递到MQ, orderId => {}", orderId);
    }
}
